#include "wl_trace.h"
#include "wl_core.h"
#include "wl_utils.h"
#include <stdio.h>
#include <string.h>

#define CUR_WLLOG_LEVEL WLLOG_ERROR_LEVEL
#define TRACE_BUF_SIZE 256

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

static wl_trace_callback s_trace_callback;
static wl_char           s_trace_level[WLLOG_LEVEL_MAX][10] = {"TRACE", "INFO", "DEBUG", "WARN", "ERROR"};
static wl_bool           s_trace_init;

static wl_int32 trace_message_callback(wl_int32 msgid, void* data, wl_uint32 datalen) {
    if (s_trace_callback) {
        // s_trace_callback((wl_char*)data);
    }
}

void wl_trace_regist_callback(wl_trace_callback callback) {
    s_trace_callback = callback;
}

void wl_trace_init(void) {
#ifdef OSAL_DEBUG
    if (!s_trace_init) {
        //启动日志线程,解决卡顿问题
        wl_module module;
        memset(&module, 0, sizeof(wl_module));
        module.moduleid = WL_MODULE_TRACE;
        module.taskid   = WL_TASK_TRACE;
        module.callback = trace_message_callback;
        wl_core_register_module(&module);
        s_trace_init = wl_true;
    }
#endif
}
void wl_trace_end(void) {
#ifdef OSAL_DEBUG
    if (s_trace_init) {
        wl_core_unregister_module(WL_MODULE_TRACE);
        s_trace_init = wl_false;
    }
#endif
}

void wl_trace(wl_int32 level, const wl_char* format, ...) {
    //if (level < WLLOG_LEVEL_MAX && level >= CUR_WLLOG_LEVEL && wl_null != s_trace_callback) {
        va_list  va;
        wl_char  buf[TRACE_BUF_SIZE] = "";
        wl_int32 buflen              = 0;

        sprintf(buf, "[%d][%d][WLSDK][%s]:", wl_utctime(), wl_getElapsedTick(), s_trace_level[level]);
        buflen = strlen(buf);

        va_start(va, format);
        vsnprintf(buf + buflen, TRACE_BUF_SIZE - buflen, format, va);
        va_end(va);
        buf[255] = '\0';

#ifdef OSAL_DEBUG
        if (s_trace_init) {
            buflen      = strlen(buf);
            buf[buflen] = '\0';
            // wl_core_send_message(WL_MODULE_TRACE, 0, buf, buflen + 1);
        } else {
            s_trace_callback(buf);
        }
#else
        s_trace_callback(buf);
#endif
    //}
}

int wl_trace_weilapb(const wl_char* format, ...) {
    va_list  va;
    wl_char  buf[TRACE_BUF_SIZE] = "";
    wl_int32 buflen              = 0;

    sprintf(buf, "[%d][%d][WLSDK][ERROR]:", wl_utctime(), wl_getElapsedTick());
    buflen = strlen(buf);

    va_start(va, format);
    vsnprintf(buf + buflen, TRACE_BUF_SIZE - buflen, format, va);
    va_end(va);
    buf[255] = '\0';

#ifdef OSAL_DEBUG
    if (s_trace_init) {
        buflen      = strlen(buf);
        buf[buflen] = '\0';
        // wl_core_send_message(WL_MODULE_TRACE, 0, buf, buflen + 1);
    } else {
        s_trace_callback(buf);
    }
#else
    s_trace_callback(buf);
#endif

    return 0;
}

#ifdef __cplusplus
}
#endif /* __cplusplus */
